package com.foreknow.dao.impl;

import com.foreknow.dao.GuestbookDao;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;
import com.foreknow.model.Guestbook;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GuestbookDaoImpl extends BaseDao implements GuestbookDao {
    @Override
    public boolean save(Guestbook gb) throws SQLException {
        String sql = "insert into guestbook(name,phone,email,title,content,createdtime) values(?,?,?,?,?,?)";
        int isRight = jt.update(sql,gb.getName(),gb.getPhone(),gb.getEmail(),gb.getTitle(),gb.getContent(),gb.getCreatedtime());
        return isRight == 1;
    }

    @Override
    public List<Guestbook> getAllMessage() {
        String sql = "select * from guestbook";
        List<Guestbook> guestbookList = new ArrayList<>();
        EntityMapping mapping = mappingFactory.getMapping(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list = jt.query(sql,mapping);
        //遍历List集合并将对象保存到新的List集合中
        for(int i = 0;i<list.size();i++) {
            Guestbook gb = (Guestbook) list.get(i);
            guestbookList.add(gb);
        }
        return guestbookList;
    }

    @Override
    public boolean deleteById(int id) throws SQLException{
        String sql = "delete from guestbook where id=?";
        int isRight = jt.update(sql,id);
        return isRight == 1;
    }
}
